﻿using DAO;
using DTO;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GUI.Properties;
using System.Threading;
using System.Globalization;

namespace GUI
{
    public partial class frmChon : Form
    {
        DataTable pinTheoLoai;
        DataTable loaiPin;
        bool _loaded = false;
        bool _autoCal = true;

        public frmChon(string a)
        {
            InitializeComponent();
            lbTongCSTB.Text = a;
        }
        private void frmChon_Load(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Maximized;
            LoadKhuVuc();
            LoadLoaiPin();
            Update_ComboboxTenPin_TienMoiWatt();
            _loaded = true;
            Update_ThongTinLoaiPin();
            Update_PinCanThiet();
            _loaded = true;
            //Update_SoLuong();
        }


        private void lbTongCSPin_TextChanged(object sender, EventArgs e)
        {
            Update_TrangThai();
            Update_SoLuong();
            if (lbTongCSPin.Text == "0")
                btnThem.Enabled = true;
        }
        private void cbbLoaiPin_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (_loaded == true)
            {
                Update_ComboboxTenPin_TienMoiWatt();
                if (_autoCal == true)
                {
                    gvPin.Rows.Clear();
                    //TrangThai(false);
                }
                btnThem.Enabled = true;
            }
        }

        private void cbbSoGioNang_TextChanged(object sender, EventArgs e)
        {
            if (_loaded == true)
            {
                Update_PinCanThiet();
            }
        }
        private void gvPin_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (_loaded == true)
            {
                if (gvPin.CurrentRow.Cells["clSl"].Value != null)
                {
                    int _cs = int.Parse(gvPin.CurrentRow.Cells["clCongSuat"].Value.ToString());
                    int _sl = int.Parse(gvPin.CurrentRow.Cells["clSl"].Value.ToString());
                    int _tongCS = _cs * _sl;

                    gvPin.CurrentRow.Cells["clTongCS"].Value = _tongCS.ToString();
                    Update_TongPinDaChon_TongTien();
                }
            }

        }
        private void cbbTenPin_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (_loaded == true)
            {
                if (btnThem.Enabled == false)
                    gvPin.Rows.Clear();
                Update_ThongTinLoaiPin();
                Update_SoLuong();
            }
        }
        private void CheckedChanged(object sender, EventArgs e)
        {
            gvPin.Rows.Clear();
            if (rdoTuDong.Checked == true)
            {
                _autoCal = true;
            }
            else
            {
                _autoCal = false;
            }
            btnThem.Enabled = true;
            Update_SoLuong();
        }

        private void txtWatt_DoubleClick(object sender, EventArgs e)
        {
            txtWatt.ReadOnly = false;
            btnSua.Visible = true;
        }
        private void btnSua_Click(object sender, EventArgs e)
        {
            LoaiPinDTO _lp = new LoaiPinDTO();
            LoaiPinDAO _lpDAO = new LoaiPinDAO();
            _lp.MALPIN = (int)cbbLoaiPin.SelectedValue;
            _lp.TENLOAI = cbbLoaiPin.Text;
            _lp.TIENMOIWATT = int.Parse(txtWatt.Text);
            int kq = _lpDAO.SuaLoaiPin(_lp);

            txtWatt.ReadOnly = true;
            btnSua.Visible = false;
            if (kq != 0)
            {
                int _vt = cbbLoaiPin.SelectedIndex;
                Update_GioHang();
                _loaded = false;
                LoadLoaiPin();
                cbbLoaiPin.SelectedIndex = _vt;
                _loaded = true;
            }
            else
                MessageBox.Show("Cập nhật thất bại");
        }
        private void btnThem_Click(object sender, EventArgs e)
        {

            int n = gvPin.Rows.Count - 1;
            for (int i = 0; i < n; i++)
            {
                if (int.Parse(cbbTenPin.SelectedValue.ToString()) == int.Parse(gvPin.Rows[i].Cells["clSTT_Pin"].Value.ToString()))
                {
                    if (_autoCal == false)
                    {
                        formNhapSoLuongPin _frmNhapSL = new formNhapSoLuongPin();
                        _frmNhapSL.SlPin = int.Parse(gvPin.Rows[i].Cells["clSl"].Value.ToString());
                        _frmNhapSL.ShowDialog();
                        if (_frmNhapSL.SlPin == -1)
                            return;
                        gvPin.Rows[i].Cells["clSl"].Value = _frmNhapSL.SlPin;
                    }
                    return;
                }
            }
            if (_autoCal == false)
            {
                formNhapSoLuongPin _frmNhapSL = new formNhapSoLuongPin();
                _frmNhapSL.SlPin = int.Parse(lbSL.Text);
                _frmNhapSL.ShowDialog();
                if (_frmNhapSL.SlPin == -1)
                    return;
                lbSL.Text = _frmNhapSL.SlPin.ToString();
            }
            if (int.Parse(lbSL.Text) == 0)
                return;
            ThemVaoLuoi();
            if (_autoCal == true && int.Parse(lbSL.Text)>0)
            {
                n = gvPin.Rows.Count - 1;
                cbbTenPin.SelectedIndex = LoadMaxCan();

                int _tongCSC = int.Parse(lbTongCSCan.Text);
                int _tongCSPin = int.Parse(lbTongCSPin.Text);
                int _csPin = int.Parse(lbCS.Text);
                int _csConLai = _tongCSC - _tongCSPin;
                int _sl = _csConLai / _csPin;
                lbSL.Text = (_sl + 1).ToString();
                for (int i = 0; i < n; i++)
                {
                    if (int.Parse(gvPin.Rows[i].Cells[0].Value.ToString()) == int.Parse(cbbTenPin.SelectedValue.ToString()))
                        gvPin.Rows[i].Cells["clSl"].Value = int.Parse(gvPin.Rows[i].Cells["clSl"].Value.ToString()) + int.Parse(lbSL.Text);
                    else
                        ThemVaoLuoi();
                }
            }
        }

        private void btnHuy_Click(object sender, EventArgs e)
        {
            gvPin.Rows.Clear();
        }
        private void btnDong_Click(object sender, EventArgs e)
        {
            Close();
        }
        private void rdoThuCong_Click(object sender, EventArgs e)
        {
            rdoThuCong.Checked = true;
            rdoTuDong.Checked = false;
        }
        private void rdoTuDong_Click(object sender, EventArgs e)
        {
            rdoTuDong.Checked = true;
            rdoThuCong.Checked = false;
        }


        private void gvPin_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            Update_TongPinDaChon_TongTien();
        }


        private void lbTongCSCan_TextChanged(object sender, EventArgs e)
        {
            if (_loaded == true)
            {
                gvPin.Rows.Clear();
                Update_TrangThai();
                Update_SoLuong();
            }
        }

        //----------------------------------------------
        private void Update_PinCanThiet()
        {
            float _tongCSTB = float.Parse(lbTongCSTB.Text);
            float _soGioNang = 1;

            try
            {
                _soGioNang = float.Parse(cbbSoGioNang.Text.ToString());
            }
            catch
            {
                try
                {
                    _soGioNang = float.Parse(cbbSoGioNang.SelectedValue.ToString());
                }
                catch (Exception)
                {
                    MessageBox.Show("Khu vực chưa có hoặc sai định dạng!");
                }
            }

            float _csC = float.Parse(_tongCSTB.ToString()) / _soGioNang;
            int _tCSC = (int)(_csC + 0.5);
            lbTongCSCan.Text = _tCSC.ToString();

        }
        private void Update_TrangThai()
        {
            try
            {
                int _tongCSC = int.Parse(lbTongCSCan.Text);
                int _tongCSDC = int.Parse(lbTongCSPin.Text);
                int _csConThieu = _tongCSC - _tongCSDC;
                if (_csConThieu > 0)
                {
                    lbTrangThaiCS.Text = "Vẫn còn thiếu " + _csConThieu.ToString() + "W";
                }
                else
                    lbTrangThaiCS.Text = "Đã đủ công suất cần thiết!";
            }
            catch (Exception)
            {
            }

        }
        private void Update_TongPinDaChon_TongTien()
        {
            try
            {
                int _tongPinDaChon = 0;
                long _tongTien = 0;
                int n = gvPin.Rows.Count - 1;
                for (int i = 0; i < n; i++)
                {
                    int _giaMoiWatt = int.Parse(gvPin.Rows[i].Cells["clGTMoiWatt"].Value.ToString());
                    int _csTrenDong = int.Parse(gvPin.Rows[i].Cells["clTongCS"].Value.ToString());

                    _tongPinDaChon += _csTrenDong;
                    _tongTien += long.Parse((_giaMoiWatt * _csTrenDong).ToString());
                }
                lbTongTien.Text = _tongTien.ToString("###,###,##0.", CultureInfo.InvariantCulture).TrimStart().Replace(".", ",");
                lbTongCSPin.Text = _tongPinDaChon.ToString();
            }
            catch (Exception)
            {
            }

        }
        private void Update_ComboboxTenPin_TienMoiWatt()
        {
            try
            {
                PinDAO _pin = new PinDAO();
                int _loaiPin = (int)cbbLoaiPin.SelectedValue;
                pinTheoLoai = _pin.LoadPin_TheoLoai(_loaiPin);
                cbbTenPin.DataSource = pinTheoLoai;
                cbbTenPin.DisplayMember = "TenTB";
                cbbTenPin.ValueMember = "STT_Pin";

                string sql = "MaLPin =" + _loaiPin.ToString();
                DataRow[] result = loaiPin.Select(sql);
                txtWatt.Text = result[0]["TienMoiWatt"].ToString();
            }
            catch (Exception)
            {
                this.Close();
                MessageBox.Show("Không có pin!");
            }

        }
        private void Update_ThongTinLoaiPin()
        {
            try
            {
                _loaded = false;
                int _sttPin = int.Parse(cbbTenPin.SelectedValue.ToString());
                string sql = "STT_Pin =" + _sttPin.ToString();
                DataRow[] result = pinTheoLoai.Select(sql);
                txtKichThuoc.Text = result[0]["KichThuoc"].ToString();
                txtImp.Text = result[0]["AMin"].ToString();
                txtVmp.Text = result[0]["VMin"].ToString();
                txtIsc.Text = result[0]["AMax"].ToString();
                txtVoc.Text = result[0]["VMax"].ToString();
                lbCS.Text = result[0]["CSKhaDung"].ToString();
                _loaded = true;
            }
            catch (Exception)
            {
            }

        }
        private void Update_SoLuong()
        {
            try
            {
                if (_loaded == true)
                {
                    int _sl = 1;
                    if (_autoCal == true)
                    {
                        int _tongCSC = int.Parse(lbTongCSCan.Text);
                        int _tongCSPin = int.Parse(lbTongCSPin.Text);
                        int _csPin = int.Parse(lbCS.Text);
                        int _csConLai = _tongCSC - _tongCSPin;

                        if (_csConLai > 0)
                        {
                            _sl = _csConLai / _csPin;
                            if (_sl == 0)
                            {
                                _sl = 1;
                            }
                            if (_csConLai - _csPin * _sl > 0)
                                _sl += 1;
                        }
                        else
                            _sl = 0;
                    }
                    lbSL.Text = _sl.ToString();
                }
            }
            catch (Exception)
            {
            }


        }
        private void Update_GioHang()
        {
            try
            {
                int n = gvPin.Rows.Count - 1;
                for (int i = 0; i < n; i++)
                {
                    if (gvPin.Rows[i].Cells["clLoaiPin"].Value.ToString() == cbbLoaiPin.Text)
                    {
                        gvPin.Rows[i].Selected = true;
                        gvPin.Rows[i].Cells["clGTMoiWatt"].Value = txtWatt.Text;
                    }
                }
            }
            catch (Exception)
            {
            }
        }

        private void LoadLoaiPin()
        {
            try
            {
                LoaiPinDAO _lp = new LoaiPinDAO();
                loaiPin = _lp.LoadLoaiPin_TheoPin();
                cbbLoaiPin.DataSource = loaiPin;
                cbbLoaiPin.DisplayMember = "TenLoai";
                cbbLoaiPin.ValueMember = "MaLPin";
            }
            catch (Exception)
            {
            }
        }
        private void LoadKhuVuc()
        {
            try
            {
                KhuVucDAO _kv = new KhuVucDAO();
                cbbSoGioNang.DataSource = _kv.LoadKhuVuc();
                cbbSoGioNang.DisplayMember = "TenKV";
                cbbSoGioNang.ValueMember = "SoGioNang";
            }
            catch (Exception)
            {
            }
        }
        private void Load_Pict_info(string channel)
        {
            object o = Properties.Resources.ResourceManager.GetObject(channel);
            if (o is Image)
            {
                pictPin.Image = o as Image;
            }
        }
        private int LoadMaxCan()
        {
            try
            {
                int n = gvPin.Rows.Count - 1;
                int _maxIndex = 0;
                int _sl = 0;
                int _tongCSC = int.Parse(lbTongCSCan.Text);
                int _tongCSPin = int.Parse(lbTongCSPin.Text);
                cbbTenPin.SelectedIndex = 0;
                int _csPin = int.Parse(lbCS.Text);
                int _csConLai = _tongCSC - _tongCSPin;
                _sl = int.Parse((_csConLai / _csPin).ToString());
                if (_sl * _csPin < _csConLai)
                    _sl++;

                int _csHH = _sl * _csPin - _csConLai;
                for (int i = 1; i <= n; i++)
                {
                    cbbTenPin.SelectedIndex = i;
                    _csPin = int.Parse(lbCS.Text);
                    int _slTamThoi = int.Parse((_csConLai / _csPin).ToString());
                    if (_slTamThoi * _csPin < _csConLai)
                        _slTamThoi++;
                    if (_csHH >= _slTamThoi * _csPin - _csConLai)
                    {
                        if (_sl > _slTamThoi)
                        {
                            _csHH = _slTamThoi * _csPin - _csConLai;
                            _sl = _slTamThoi;
                            _maxIndex = i;
                        }
                    }
                }
                return _maxIndex;
            }
            catch (Exception)
            {
                return 0;
            }

        }
        private void ThemVaoLuoi()
        {
            try
            {
                DataGridViewRow row = (DataGridViewRow)gvPin.Rows[0].Clone();
                row.Cells[0].Value = cbbTenPin.SelectedValue;
                row.Cells[1].Value = cbbLoaiPin.Text;
                row.Cells[2].Value = cbbTenPin.Text;
                row.Cells[3].Value = lbSL.Text;
                row.Cells[4].Value = txtKichThuoc.Text;
                row.Cells[5].Value = txtImp.Text;
                row.Cells[6].Value = txtVmp.Text;
                row.Cells[7].Value = txtIsc.Text;
                row.Cells[8].Value = txtVoc.Text;
                row.Cells[9].Value = txtWatt.Text;
                row.Cells[10].Value = lbCS.Text;
                row.Cells[11].Value = int.Parse(lbCS.Text) * int.Parse(lbSL.Text);

                gvPin.Rows.Insert(gvPin.Rows.Count - 1, row);
                if (_autoCal == false)
                    gvPin.Rows[gvPin.Rows.Count - 2].Cells[3].ReadOnly = false;
                else
                    gvPin.Rows[gvPin.Rows.Count - 2].Cells[3].ReadOnly = true;
                Update_TongPinDaChon_TongTien();
                
                if(_autoCal==true)
                    btnThem.Enabled = false;
            }
            catch (Exception)
            {
            }
        }

        private void gvPin_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            TextBox a = e.Control as TextBox;
            a.Name = "";
            if (gvPin.CurrentCellAddress.X == gvPin.Columns[3].DisplayIndex)
            {
                if (a != null)
                {
                    a.Name = "txt";
                    a.KeyPress += new KeyPressEventHandler(a_KeyPress);
                }
            }
        }

        void a_KeyPress(object sender, KeyPressEventArgs e)
        {
            string decimalString = Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencyDecimalSeparator;
            char decimalChar = Convert.ToChar(decimalString);
            TextBox a = sender as TextBox;
            if (Char.IsDigit(e.KeyChar) || Char.IsControl(e.KeyChar)) { }
            else if (e.KeyChar == decimalChar && a.Text.IndexOf(decimalString) == -1)
            { }
            else
            {
                e.Handled = true;
            }
        }

        private void cbbSoGioNang_Leave(object sender, EventArgs e)
        {
            if (cbbSoGioNang.Text != "")
            {
                try
                {
                    if (float.Parse(cbbSoGioNang.Text) > 12)
                    {
                        MessageBox.Show("Số giờ nắng không thể lớn hơn 12", "Cảnh báo");
                        cbbSoGioNang.SelectedIndex = 0;
                        return;
                    }
                }
                catch
                { }
            }
        }

        private void cbbSoGioNang_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void lbThietBiKem_Click(object sender, EventArgs e)
        {
            frmThietBiNgoaiVi _frm = new frmThietBiNgoaiVi(int.Parse(lbTongCSPin.Text));
            _frm.ShowDialog();
        }


    }
}
